﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using LY.Common.Utils.Sf_Struct;
 
using Newtonsoft.Json;
using LY.Entity.PageSearch;
using LY.Interface;
using LY.Entity.SearchEntity;
using LY.Entity.Entities;
using LY.Entity.Jsons;
using LY.Entity;
using LY.Common.Utils;
using System.Xml;
using System.IO;
using System.Collections;
using QJ.CMS.ShengPayB2C;
using QJ.CMS.ShengPayQueryOrder;
using extension = QJ.CMS.ShengPayB2C.extension;
using header = QJ.CMS.ShengPayB2C.header;
using sender = QJ.CMS.ShengPayB2C.sender;
using service = QJ.CMS.ShengPayB2C.service;
using signature = QJ.CMS.ShengPayB2C.signature;


namespace QJ.CMS.Areas.Admin.Controllers
{
    public class FinanceMgrController : Controller
    {
        private IProjectService _projectService;
        private IT_ProjectService _tprojectService;
        private IInvestService _investService;
        private IFundsFlowService _fundsFlowService;
        private IClaimsService _cservice;
        //
        // GET: 财务管理
        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];
        //支付的商户号
        private static string _zfmysenderId = ConfigurationManager.AppSettings["ZFmysenderId"];
        private static string _zfkey = ConfigurationManager.AppSettings["ZFKey"];

        public FinanceMgrController(IProjectService projectService, IT_ProjectService tprojectService, IInvestService investService, IFundsFlowService fundsFlowService, IClaimsService cSercive)
        {
            _projectService = projectService;
            _tprojectService = tprojectService;
            _investService = investService;
            _fundsFlowService = fundsFlowService;
            _cservice = cSercive;
        }

        #region 平台账户管理
        /// <summary>
        /// 平台账户管理，账户余额
        /// </summary>
        /// <returns></returns>
        public ActionResult AccountBalance()
        {
            var m = LY.ShengPayApi.Services.Get.GetMerchantAccount(_apiAddress, _merchantNo, _merchantNo);
            return View(m);
        }
        #endregion

        #region 退款管理
        //退款管理
        public ActionResult RefundManagement()
        {
            return View();
        }

        //退款管理列表
        [HttpPost]
        public ActionResult RefundManagementList(FormCollection collection, ProjectOrderSearch search)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
            search.PayStatus = 5;//退款中
            PagedList<R_ProjectOrder_EX> bList = _projectService.QueryProjectOrder(view, search);
            JsonQTable at = JsonQTable.ConvertFromPagedList<R_ProjectOrder_EX>(bList, colkey, colsinfo.Split(','));
            return Json(at); 
        }

        //退款
        public ActionResult ReFund(string projectOrderId)
        {
            JsonSMsg rMsg = new JsonSMsg();
            R_ProjectOrder order = _projectService.GetProjectOrder(int.Parse(projectOrderId));
            refundResponse result = ReFundWebservice(order);
            if (result.returnInfo.errorMsg == "原始订单状态不是支付成功，不允许退款！")
            {
                rMsg.Message = "原始订单状态不是支付成功，不允许退款！";
                rMsg.Status = 1;
                return Json(rMsg);
            }
            //R_ProjectOrder returnorder = _projectService.GetProjectOrder(int.Parse(result.originalOrderNo));
            if (result.status == "00")
            {
                rMsg.Message = "处理中";
                rMsg.Status = 0;
            }
            else if (result.status == "01")
            {
                rMsg.Message = "退款成功";
                rMsg.Status = 1;
                order.PayStatus = 6;
            }
            else
            {
                rMsg.Message = "退款失败";
                rMsg.Status = -1;
                order.PayStatus = 7;
            }
            _projectService.SaveProjectOrder(order);
            return Json(rMsg);
        }

        public refundResponse ReFundWebservice(R_ProjectOrder order)
        {
            string mysenderId = _zfmysenderId;
            string sendTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string refundOrderNo = DateTime.Now.ToString("MMddHHmmssfff") + new Random().Next(0, 999);//这里只能14位
            string sign = "REFUND_REQ" + "|" + "V4.4.1.1.1" + "|" + "UTF-8" + "|" + _zfmysenderId + "|"
                          + sendTime + "|" + _zfmysenderId + "|" + refundOrderNo + "|" + order.SerialNumber + "|"
                          + order.Amount + "|" + "0" + "|" + _backAddress + "/Pay/ReFundNotifyUrl" + "|" + "beizhu" +
                          "|" + "MD5" + "|";
            sign = MD5Util.GetMD5_32(sign + _zfkey).ToUpper();
            var apiClient = new RefundAPIClient();
            var _service = new service
            {
                serviceCode = "REFUND_REQ",
                version = "V4.4.1.1.1"
            };
            var _sender = new sender
            {
                senderId = _zfmysenderId
            };
            var _header = new header
            {
                charset = "UTF-8",
                sendTime = sendTime,
                sender = _sender,
                service = _service
            };

            var refund = new refundRequest
            {
                header = _header,
                memo = "beizhu",
                merchantNo = _zfmysenderId,
                notifyURL = _backAddress + "/Pay/ReFundNotifyUrl",
                originalOrderNo = order.SerialNumber,
                refundAmount = order.Amount.ToString(),
                refundOrderNo = refundOrderNo,
                refundRoute = "0",
                signature = new signature { signMsg = sign, signType = "MD5" }
            };
            var result = apiClient.processRefund(refund);
            return result;
        }

        //查询订单情况
        public ActionResult QueryfundUrl(string projectOrderId)
        {
            string mysenderId = _zfmysenderId;
            R_ProjectOrder order = _projectService.GetProjectOrder(int.Parse(projectOrderId));
            string sendTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string sign = "QUERY_ORDER_REQUEST" + "|" + "V4.3.1.1.1" + "|" + "UTF-8" + "|" + _zfmysenderId + "|"
                          + sendTime + "|" + _zfmysenderId + "|" + order.SerialNumber + "|" + "MD5" + "|";
            sign = MD5Util.GetMD5_32(sign + _zfkey).ToUpper();
            var apiClient = new QueryOrderAPIClient();
            QJ.CMS.ShengPayQueryOrder.service ser = new QJ.CMS.ShengPayQueryOrder.service();
            ser.serviceCode = "QUERY_ORDER_REQUEST";
            ser.version = "V4.3.1.1.1";
            QJ.CMS.ShengPayQueryOrder.sender sen = new QJ.CMS.ShengPayQueryOrder.sender();
            sen.senderId = mysenderId;
            QJ.CMS.ShengPayQueryOrder.header hea = new QJ.CMS.ShengPayQueryOrder.header();
            hea.charset = "UTF-8";
            hea.sender = sen;
            hea.sendTime = sendTime;
            hea.service = ser;
            QJ.CMS.ShengPayQueryOrder.signature signa = new QJ.CMS.ShengPayQueryOrder.signature();
            signa.signType = "MD5";
            signa.signMsg = sign;
            orderQueryRequest orderQuery = new orderQueryRequest();
            orderQuery.header = hea;
            orderQuery.merchantNo = _zfmysenderId;
            orderQuery.orderNo = order.SerialNumber;
            orderQuery.signature = signa;
            var result = apiClient.queryOrder(orderQuery);
            //校验签名
            string Origin = result.header.service.serviceCode + "|" + result.header.service.version + "|"
                            + result.header.charset + "|" + result.header.traceNo + "|" + result.header.sender.senderId + "|"
                            + result.header.sendTime + "|" + result.orderNo + "|" + result.orderAmount + "|"
                            + result.transNo + "|" + result.transAmoumt + "|" + result.transStatus + "|"
                            + result.transTime + "|" + result.signature.signType + "|";
            if (MD5Util.GetMD5_32(Origin + _zfkey).ToUpper() == result.signature.signMsg)
            {
                ViewBag.result = "验证成功";
                ViewBag.TraceNo = result.header.traceNo;
                ViewBag.SendTime = result.header.sendTime;
                ViewBag.OrderNo = result.orderNo;
                ViewBag.OrderAmount = result.orderAmount;
                ViewBag.TransNo = result.transNo;
                ViewBag.TransAmoumt = result.transAmoumt;
                switch (result.transStatus)
                {
                    case "00": ViewBag.TransStatus = "等待付款中"; break;
                    case "01": ViewBag.TransStatus = "付款成功"; break;
                    case "02": ViewBag.TransStatus = "付款失败"; break;
                    case "03": ViewBag.TransStatus = "过期"; break;
                    case "04": ViewBag.TransStatus = "撤销成功"; break;
                    case "05": ViewBag.TransStatus = "退款中"; break;
                    case "06": ViewBag.TransStatus = "退款成功"; break;
                    case "07": ViewBag.TransStatus = "退款失败"; break;
                    case "08": ViewBag.TransStatus = "部分退款成功"; break;
                    default: ViewBag.TransStatus = "Unknown"; break;
                }
                ViewBag.TransTime = result.transTime;
            }
            else
            {
                ViewBag.result = "验证失败";
            }
            return View();
        }
        #endregion

        #region 失败项目退款
        //失败项目退款
        public ActionResult ProjectRefund()
        {
            return View();
        }

        //所有已失败的项目
        public ActionResult ProjectRefundList(FormCollection collection, ProjectSearch search)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
            search.ProjectStatus = "6";
            PagedList<ProjectEx> bList = _projectService.QueryProject(search, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<ProjectEx>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        //已失败项目的投资成功的列表
        public ActionResult ProjectOrderDetail()
        {
            ViewBag.ProjectId = Request["ProjectId"];
            return View();
        }

        //众筹订单列表,projectID=6 失败的项目订单，paystatus=1 用户已支付成功的
        public ActionResult ProjectOrderDetailList(FormCollection collection, ProjectOrderSearch search)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string  colsinfo = collection["colsinfo"];
            //search.ProjectId = int.Parse(Request["ProjectId"]);
            search.PayStatus = 1;
            var bList = _projectService.QueryProjectOrder(view, search);
            JsonQTable at = JsonQTable.ConvertFromPagedList<R_ProjectOrder_EX>(bList, colkey, colsinfo.Split(','));
            return Json(at);
        }

        //把该失败项目的所有支付过的人钱 退款处理
        public ActionResult ReFundByProjectId(int projectId)
        {
            List<R_ProjectOrder> list = _projectService.QueryProjectOrderList(projectId, 1);
            for (int i = 0; i < list.Count; i++)
            {
                refundResponse refundresponse = ReFundWebservice(list[i]);
                if (refundresponse.status==null) //某一笔订单不存在
                {
                    return Content(list[i].SerialNumber+"订单不存在");
                }
                if (refundresponse.returnInfo.errorMsg == "原始订单状态不是支付成功，不允许退款！")
                {
                    return Content("原始订单状态不是支付成功，不允许退款！");
                }
                if (refundresponse.status == "01") //退款成功
                {
                    list[i].PayStatus = 6;
                }
                if (refundresponse.status == "02") //退款失败
                {
                    list[i].PayStatus = 7;
                    return Content( list[i].MemberId+"退款失败");
                }
                _projectService.SaveProjectOrder(list[i]);
            }
            return Content("全部退款成功");
        }
        #endregion

        #region 投标溢出处理
        public ActionResult OverFlowBiao()
        {
            return View();
        }

        public ActionResult OverFlowBiaoList(FormCollection collection, ProjectSearch search)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
            PagedList<T_Project_EX> bList = _tprojectService.QueryOverFlowProjectList(search,view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<T_Project_EX>(bList, colkey, colsinfo.Split(','));
            return Json(at); 
        }

        //撤销用户投标
        public ActionResult RevokeBiao()
        {
            ViewBag.ProjectId = Request["ProjectId"];
            return View();
        }

        //溢出标的投资情况
        public ActionResult InvestmentList(FormCollection collection, InvestSearch search)
        {
            PageView view = new PageView(collection);
            string colkey = collection["colkey"];
            string colsinfo = collection["colsinfo"];
            PagedList<T_Investment> bList = _investService.QueryInvestmentList(search, view);
            JsonQTable at = JsonQTable.ConvertFromPagedList<T_Investment>(bList, colkey, colsinfo.Split(','));
            return Json(at); 
        }

        //撤销多余的标 这里是处理逻辑
        public ActionResult RevokeOverFlowBiao(int id)
        {
            T_Investment investment = _investService.GetModel(id);
            T_Project project = _tprojectService.GetModel(investment.ProjectId);
            string result = LY.ShengPayApi.Services.Delete.DeleteP2PBidSubmitBid(_apiAddress, _merchantNo, project.ProjectNo,investment.SubmitBidNo);
            if (result.Contains("请求成功完成")) //表示撤销成功
            {
                try
                {
                    investment.Status = 0;
                    _investService.SaveInvestment(investment);
                    U_FundsFlow fundsFlow = _fundsFlowService.GetFundsFlowByOrderNo(investment.SubmitBidNo);
                    fundsFlow.Status = 0;
                    _fundsFlowService.UpdateFundsFlow(fundsFlow);
                    var amounts = _cservice.GetAmountsByPid(project.ID.ToString());
                    if (project.TotalLoan >= amounts)
                    {
                        string apireturn = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_merchantNo, project.ProjectNo, 2, _backAddress + "/Pay/ManBiaoNotifyUrl", "0.00", _apiAddress);
                        if (apireturn.Contains("请求成功完成"))
                        {
                            return Content("满标成功");
                        }
                        else
                        {
                            return Content("满标失败");
                        }
                    }

                }
                catch (Exception ex)
                {
                    return Content("撤销投标成功，但是数据库更新状态出错！");
                }
            }
            else
            {
                return Content("撤销失败");
            }
            return Json("请求成功完成");
        }

        //满标
        public ActionResult ManBiao(int id)
        {
            T_Project project = _tprojectService.GetModel(id);
            var amounts = _cservice.GetAmountsByPid(id.ToString());
            if (project.TotalLoan < amounts)
            {
                return Content("当前的标投资还是溢出");
            }
            else
            {
                string result = LY.ShengPayApi.Services.Put.PutP2PBidEvent(_merchantNo, project.ProjectNo, 2, _backAddress + "/Pay/ManBiaoNotifyUrl", "0.00", _apiAddress);
                if (result.Contains("请求成功完成"))
                {
                    return Content("满标成功");
                }
                else
                {
                    return Content("满标失败");
                }
            }
        }

        #endregion

        public ActionResult Test()
        {
            JsonSMsg rMsg = new JsonSMsg();
            R_ProjectOrder order = _projectService.GetProjectOrder(220);
            refundResponse result = ReFundWebservice(order);
            if (result.returnInfo.errorMsg == "原始订单状态不是支付成功，不允许退款！")
            {
                rMsg.Message = "原始订单状态不是支付成功，不允许退款！";
                rMsg.Status = 1;
                return Json(rMsg);
            }
            R_ProjectOrder returnorder = _projectService.GetProjectOrder(int.Parse(result.originalOrderNo));
            if (result.status == "00")
            {
                rMsg.Message = "处理中";
                rMsg.Status = 0;
            }
            else if (result.status == "01")
            {
                rMsg.Message = "退款成功";
                rMsg.Status = 1;
                returnorder.PayStatus = 6;
            }
            else
            {
                rMsg.Message = "退款失败";
                rMsg.Status = -1;
                returnorder.PayStatus = 7;
            }
            _projectService.SaveProjectOrder(returnorder);
            return Json(rMsg);
            return null;
        }

    }
}
